public without sharing class WeiXinRepairController {
	private static final String TOPIC_NAME = 'WechatCaseStreaming';
	private static final String TOPIC_NAME_HANDLE = 'WechatCaseStreamingHandle';

	public List<CaseBean> caseList {get;set;}
	public String  newcase {get;set;}
	public String channel{get; private set;}
	public String channel2{get; private set;}
    public Integer replayFrom{get;set;}
    public String topicId {get;set;}
    public String handletopicId {get;set;}
    public Boolean ishasUndealCase {get;set;}
    public String opttype {get;set;}//操作类型
    public Map<Id,CaseBean>  casMap;
    public Boolean isHasRight {get;private set;}//是否有权限

    public String responsecode {get;private set;}//当前用户的服务编码

    public String  codeJson {get;private set;}//

    public Boolean isOwner {get;private set;}//是否是自己的单子

    public User currentUser ;//当前用户

    public Boolean isPlayAlarm {get;private set;} //是否播放 警报

    public  Map<String,Id>  rsCodeMap ;///记录可以操作的服务主体 服务编码 及对应的 优先处理人
    public Map<String ,String>  subMap ;

    public WeiXinRepairController() {
        this.channel = '/topic/' + TOPIC_NAME;
        this.channel2 = '/topic/' + TOPIC_NAME_HANDLE;

    	replayFrom = -1;
        caseList = new List<CaseBean>();
        casMap= new Map<Id,CaseBean>();
        rsCodeMap= new Map<String,Id>();
        subMap = new Map<String,String>();

    }
    public void  init(){

        currentUser = [select ResponseCode__c,Id,Profile.Name ,subCompany__c from User where Id=:UserInfo.getUserId()];
        responsecode = currentUser.ResponseCode__c;

        isHasRight = currentUser.ResponseCode__c != null ;
        subMap = getPicklistValues('ResponsibleServer__c','subCompany__c');
        if(isHasRight){
            if(currentUser.Profile.Name == '迈克经销商'){
                 rsCodeMap.put(currentUser.ResponseCode__c,currentUser.Id);
              
            }else{

                ////找到所有的 经销商对应的
                String subc = subMap.get(currentUser.SubCompany__c);
                System.debug('subc');//分管公司 = 当前用户对应公司 or 
                for(ResponsibleServer__c rs :[select Id, ResponseCode__c,PriorityUser__c from ResponsibleServer__c where subCompany__c =:subc or ResponseCode__c =:responsecode   ]){
                    rsCodeMap.put(rs.ResponseCode__c,rs.PriorityUser__c);
                }

            }

            System.debug(rsCodeMap);
            codeJson =  EncodingUtil.urlEncode(JSON.serialize(rsCodeMap.keySet()), 'UTF-8');
              //and CreatedDate > LAST_WEEK

                    ///外部需求
                Id outRT = Utils.getRecordTypeIdByDevNameAndObjName('Service', 'Case');
                ///经销商服务工单
                Id dealerRT = Utils.getRecordTypeIdByDevNameAndObjName('ServiceOrder', 'Case');

                List<Case> cList = [select Id, OwnerId,CaseNumber ,WeChatRepairName__c , WeChatPhone__c ,
                    WechatPictureUrl__c,WeChatVoiceUrl__c,ServiceManufacture__r.ServiceAccount__r.ResponseCode__c,
                    CreatedDate,Account.Name ,ServiceManufacture__r.Product__r.Name,ServiceManufacture__r.ServiceAccount__r.subCompany__c
                     from Case where Origin = '扫码报修'  and CreatedDate >: System.now().addDays(-14)  and  ServiceManufacture__r.ServiceAccount__r.ResponseCode__c in:rsCodeMap.keySet() 
                     and Status != '关闭'  and ( (RecordTypeId=:outRT and  User__c = null) or (RecordTypeId=:dealerRT and Status != '已分配') ) order by createddate desc];


                System.debug('==='+cList);
                for(Case c :cList){
                    ///
                    System.debug('==='+c.ServiceManufacture__r.ServiceAccount__r.ResponseCode__c +'===' + currentUser.ResponseCode__c);
                    System.debug('==='+ c);
                  // if(c.ServiceManufacture__r.ServiceAccount__r.ResponseCode__c != currentUser.ResponseCode__c && ((System.now().getTime() - c.CreatedDate.getTime())/60000< 15)) continue;
                    CaseBean cb = new CaseBean(c,responsecode);
                    caseList.add(cb);
                    casMap.put(c.Id, cb);
                 
                    if(isPlayAlarm != true)isPlayAlarm  =  rsCodeMap.get(c.ServiceManufacture__r.ServiceAccount__r.ResponseCode__c) == currentUser.Id || rsCodeMap.get(c.ServiceManufacture__r.ServiceAccount__r.subCompany__c) == currentUser.Id;
                }
                System.debug(isPlayAlarm);
                //ishasUndealCase = caseList.size() > 0;
                this.getOrCreatedTopic(); 
           
        }else{
            codeJson =  EncodingUtil.urlEncode(JSON.serialize('[]'), 'UTF-8');
        }
    	
    }

     //获得PickList的值
    public  Map<String, String> getPicklistValues(String sObjectName, String sFieldName){
        Map<String, String> picValues= new Map<String, String>();
        Map<String, Schema.SObjectType> sObjectDescribeMap = Schema.getGlobalDescribe();
        if (sObjectDescribeMap.containsKey(sObjectName)) {
            Map<String, Schema.SobjectField> sObjectFieldsMap = 
               sObjectDescribeMap.get(sObjectName).getDescribe().fields.getMap();
            if (sObjectFieldsMap.containsKey(sFieldName)) {
                Schema.DescribeFieldResult sObjectFieldDescribe = sObjectFieldsMap.get(sFieldName).getDescribe();
                List<Schema.PicklistEntry> lPickEntryList = sObjectFieldDescribe.getPicklistValues();
                for (Schema.PicklistEntry tPicklistEntry : lPickEntryList) {
                    if(tPicklistEntry.isActive() == true){
                        picValues.put(tPicklistEntry.getLabel(),tPicklistEntry.getValue());
                    }
                    /*picValues.put(tPicklistEntry.getValue(), new Map<String,object>{
                        'value' => tPicklistEntry.getValue(),
                        'isActive' => tPicklistEntry.isActive(),
                        'isDefaultValue' => tPicklistEntry.isDefaultValue(),
                        'label' => tPicklistEntry.getLabel()
                    });*/
                }
            } else {
                //TODO 不存在此字段的执行
            }
        } else {
            // TODO 不存在此sObject的执行
        }
        return picValues;
    }
    public void newCase(){
        
    	if(newcase != null && newcase.length() > 0){
    		List<Case> newList = new List<Case>();
    		for (Case c : [select Id, CaseNumber,OwnerId ,ServiceManufacture__r.ServiceAccount__r.ResponseCode__c ,WeChatRepairName__c , WeChatPhone__c ,
    		WechatPictureUrl__c,WeChatVoiceUrl__c,ServiceManufacture__r.ServiceAccount__r.subCompany__c,
    		CreatedDate,Account.Name ,ServiceManufacture__r.Product__r.Name from Case where Id =:newcase]){
    			if(!casMap.containsKey(c.Id)){
                    CaseBean cb = new CaseBean(c,responsecode); 
    				if(caseList.size() >0){

    					caseList.add(0, cb);
    				}else{
    					caseList.add(cb);
    				}
                    casMap.put(c.Id, cb);
    			}
    			newList.add(c);

    		}
    		
    		newcase = '';
    	}
        isPlayAlarm = false;
        for (CaseBean cb: caseList) {
             isPlayAlarm  = rsCodeMap.get(cb.c.ServiceManufacture__r.ServiceAccount__r.ResponseCode__c) == currentUser.Id || rsCodeMap.get(cb.c.ServiceManufacture__r.ServiceAccount__r.subCompany__c) == currentUser.Id;
             if(isPlayAlarm) break;
        }

    }
    public void remove(){
        isPlayAlarm = false;
		if(newcase != null && casMap.containsKey(newcase)){
			casMap.remove(newcase);

    		Integer i = 0;
	    	for (CaseBean cb : caseList ) {
				if (cb.c.Id == newcase) {
					break;
				}
				i ++;
			}
			caseList.remove(i);
		}
		newcase = '';
		//ishasUndealCase = caseList.size() > 0;
        for (CaseBean cb: caseList) {
             isPlayAlarm  = rsCodeMap.get(cb.c.ServiceManufacture__r.ServiceAccount__r.ResponseCode__c) == currentUser.Id || rsCodeMap.get(cb.c.ServiceManufacture__r.ServiceAccount__r.subCompany__c) == currentUser.Id;
             if(isPlayAlarm) break;
        }


    }

    public void getOrCreatedTopic(){
    	 List<PushTopic> pushTopics = [SELECT Id,Name FROM PushTopic WHERE Name=:TOPIC_NAME];
         System.debug('***'+pushTopics);
        if (null == pushTopics || pushTopics.size() == 0) {
            PushTopic topic = new PushTopic();
            topic.Name = TOPIC_NAME;
            topic.Query = 'SELECT Id,Professional__c,Status,Origin ,ResponseCode__c,CreatedDate,OwnerId FROM Case where Origin = \'扫码报修\'';
            topic.NotifyForFields = 'Select';
            topic.ApiVersion = 40.0;
            topic.NotifyForOperationCreate = true;
			topic.NotifyForOperationUpdate = true;
			topic.NotifyForOperationUndelete = true;
			topic.NotifyForOperationDelete = true;

            If(!System.Test.isRunningTest())insert topic;
            this.topicId = topic.Id;

        } else {
            this.topicId = pushTopics.get(0).Id;
        }
    }
    
    public class CaseBean {
    	public Boolean isHandlered {get;set;}
    	public Case  c {get;set;}
    	public String cdate {get;set;}
        public Boolean isFromDealer {get;set;}//是否来自经销商

    	public CaseBean(Case record,String code){
    		isHandlered = false ;
    		c = record;
    		cdate = c.CreatedDate.format();
            isFromDealer = record.ServiceManufacture__r.ServiceAccount__r.ResponseCode__c == code ;
    	}



    }

}